home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: news.inap.net!news1!ind-000-236-45
- From: dlmiller@iquest.net (Doug Miller)
- Subject: Re: reversing a string
- X-Nntp-Posting-Host: ind-000-236-45.iquest.net
- Message-ID: <DpLtt5.Lqu@iquest.net>
- Sender: news@iquest.net (News Admin)
- Organization: IQuest Network Services
- X-Newsreader: News Xpress Version 1.0 Beta #2.1
- References: <4k6cjl$j8f@central.server.swt.edu> <4k6jks$fh9@solutions.solon.com>
- Date: Tue, 9 Apr 1996 17:00:42 GMT
-
- seebs@solutions.solon.com (Peter Seebach) wrote:
- >In article <4k6cjl$j8f@central.server.swt.edu>,
- >Leland Newsom <ln16674@nyssa.swt.edu> wrote:
- >>I have a challenge from a friend of mine. He wanted me to reverse a string
- >>with recursion without using any additional variables or loops. I got mine
- >>to work by using exclusive or, but I needed an additional variable. Can
- >>someone help with this problem without using the additional variable?
- >
- >It's trivial with something like
- > void rev (char *s) {
- > if (*s) {
- > rev(s + 1);
- > putchar(*s);
- > }
- > }
- >but this is not, strictly speaking, fair, as you're using external state
- >anyway.
- >
- >I can't see a way to reverse in place without a temporary of some sort,
- >or a loop of some sort, or something which is fundementally equivalent
- >to one of those. There may be one, but I don't know it.
- >
- >-s
-
- How about this:
-
- void swap (char *s) {
- if (strlen(s) > 1) {
- if (*s != *(s + strlen(s) - 1)) { /* fails without this if first & last chars same*/
- *s ^= *(s + strlen(s) - 1);
- *(s + strlen(s) - 1) ^= *s;
- *s ^= *(s + strlen(s) - 1);
- }
- swap (s + 1);
- }
- }
-
- void rev (char *s) {
- if (strlen(s) > 1) {
- swap (s);
- rev (s + 1);
- }
- }
-